package middleware

import (
	"context"
	"net/http"
	"server/utils"
	"server/vars"

	tojson "gitee.com/ruikc/tojson"
	"github.com/zeromicro/go-zero/rest/httpx"
)

type AdminMiddleware struct {
}

func NewAdminMiddleware() *AdminMiddleware {
	return &AdminMiddleware{}
}

func (m *AdminMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		AccessToken := r.Header.Get("Authorization")
		if AccessToken == "" {
			httpx.OkJsonCtx(r.Context(), w, tojson.NoAuth())
			return
		}
		value := utils.GetString(vars.AdminTokenPrefix + AccessToken)
		if value == "" {
			httpx.OkJsonCtx(r.Context(), w, tojson.NoAuth())
			return
		}
		jwtAdmin := &utils.JwtAdmin{}
		err := utils.JsonToStruct(value, jwtAdmin)
		if err != nil {
			httpx.OkJsonCtx(r.Context(), w, tojson.NoAuth())
			return
		}

		if jwtAdmin.Id != 1 {
			// 获取当前请求路径和方法
			path := r.URL.Path
			method := r.Method
			// 检查权限
			if !utils.CheckPermission(jwtAdmin.RoleId, path, method) {
				httpx.OkJsonCtx(r.Context(), w, tojson.NoAuth())
				return
			}
		}

		reqCtx := r.Context()
		ctx := context.WithValue(reqCtx, utils.JwtAdminKey, jwtAdmin)
		newReq := r.WithContext(ctx)
		next(w, newReq)
	}
}
